package next.fire.spinus.logx.provider.huawei.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import next.fire.spinus.logx.provider.huawei.conf.HuaweiLogConfig;
import next.fire.spinus.logx.provider.huawei.conf.HuaweiLogConfigHolder;
import next.fire.spinus.logx.utils.http.FireHttpUtils;

import java.util.Map;

/**
 * Created by daibing on 2023/4/18.
 */
public class HuaweiLogTokenClient extends HuaweiLogClient {
    public static final String LOG_TOKEN = "X-Subject-Token";

    @Override
    protected byte[] buildRawBody(String uri, String providerId, Map<String, Object> bizParams, Map<String, Object> accessParams) {
        return JSON.toJSONBytes(bizParams);
    }

    @Override
    protected byte[] buildEncodeBody(String uri, String providerId, Map<String, Object> bizParams, Map<String, Object> accessParams, byte[] rawBody) {
        return rawBody;
    }

    @Override
    protected String buildSign(Method method, String uri, String providerId, Map<String, Object> bizParams,
                               Map<String, Object> accessParams, Map<String, String> header, byte[] rawBody, byte[] encodeBody) {
        // ignore.
        return null;
    }

    @Override
    protected void loadSign(String providerId, Map<String, String> header, String sign) {
        // ignore.
    }

    @Override
    protected String buildUrl(String uri, String providerId, Map<String, Object> bizParams, Map<String, Object> accessParams, String sign) {
        HuaweiLogConfig config = HuaweiLogConfigHolder.get().select(providerId);
        if (config == null) {
            throw new RuntimeException("huawei log config not found by " + providerId);
        }
        return config.getIamEndpoint() + uri;
    }

    @Override
    protected JSONObject parse(Map<String, String> postResult, Map<String, Object> accessParams) {
        JSONObject output = new JSONObject();
        output.put(LOG_REQUEST_ID, postResult.get(LOG_REQUEST_ID));
        if (postResult.containsKey(LOG_TOKEN)) {
            output.put(LOG_TOKEN, postResult.get(LOG_TOKEN));
        }
        String content = postResult.get(FireHttpUtils.RESPONSE_BODY);
        JSONObject obj = JSON.parseObject(content);
        if (obj != null && !obj.isEmpty()) {
            output.putAll(obj);
        }
        return output;
    }
}
